package org.common4j2ee.s2shs.service.user;


import java.util.List;

import org.common4j2ee.s2shs.dao.user.UsersDaoImpl;
import org.common4j2ee.s2shs.dao.utils.Page;
import org.common4j2ee.s2shs.dao.utils.PropertyFilter;
import org.common4j2ee.s2shs.entity.user.Users;
import org.common4j2ee.s2shs.service.utils.ServiceException;
import org.common4j2ee.s2shs.service.utils.SpringSecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class UserManager {

	@Autowired
	UsersDaoImpl userDao;
	
	@Autowired    
	private  PasswordEncoder passwordEncoder;

	private static Logger logger = LoggerFactory.getLogger(UserManager.class);


	//-- User Manager --//
	@Transactional(readOnly = true)
	public Users getUser(Long id) {
		return userDao.get(id);
	}

	public void saveUser(Users entity) {
		String encodePassword=passwordEncoder.encodePassword(entity.getPassword(), null);
		entity.setPassword(encodePassword);
		userDao.save(entity);
	}

	/**
	 * 删除用户,如果尝试删除超级管理员将抛出异常.
	 */
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", SpringSecurityUtils.getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		userDao.delete(id);
	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(Long id) {
		return id == 1;
	}

	/**
	 * 使用属性过滤条件查询用户.
	 */
	@Transactional(readOnly = true)
	public Page<Users> searchUser(final Page<Users> page, final List<PropertyFilter> filters) {
		return userDao.findPage(page, filters);
	}

	@Transactional(readOnly = true)
	public Users findUserByLoginName(String loginName) {
		return userDao.findUniqueBy("loginName", loginName);
	}

	/**
	 * 检查用户名是否唯一.
	 *
	 * @return loginName在数据库中唯一或等于oldLoginName时返回true.
	 */
	@Transactional(readOnly = true)
	public boolean isLoginNameUnique(String newLoginName, String oldLoginName) {
		return userDao.isPropertyUnique("loginName", newLoginName, oldLoginName);
	}

	

	
	
}
